﻿using System;
using System.Collections.Generic;
using Rabbit.Logic;
using RabbitShop.Code;

namespace RabbitShop.UI
{
    public partial class OrderMake : System.Web.UI.Page
    {
        protected string uid = string.Empty;
        protected CartTotal CartTotal;
        protected int SelectedIndex;
        protected DiliveryPriceResult DiliveryPrice;
        protected string CompanyJson = DiliveryCompanyData.GetCompanyJson();
        protected bool IsNear = false;
        protected int Index;

        protected Shop ShopInfo;
        protected List<ShopCartItemFull> ProductList;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Cookies[Constant.CookieName] != null)
            {
                string id = Request.Cookies[Constant.CookieName].Values[Constant.CookieUid];
                if (string.IsNullOrEmpty(id))
                {
                    Response.Redirect("UserLogon.aspx");
                    return;
                }
                uid = id;

                Customer customer = RabbitUse.GetCustomerById(Db.Store, uid);
                ShopItemFull shopItemFull = RabbitUse.GetShopItemFull(Db.Store, customer);
                ShopInfo = shopItemFull.ShopInfo;
                ProductList = shopItemFull.CartItemList;

                productRepeater.DataSource = ProductList;
                productRepeater.DataBind();

                List<Address> addresses = customer.AddressList;
                addressRepeater.DataSource = addresses;
                addressRepeater.DataBind();

                SelectedIndex = customer.DefaultAddressIndex;

                Address address = customer.AddressList[SelectedIndex];

                CartTotal = NoDb.ComputeCartTotal(ProductList);

                ShipRule rule = RabbitUse.GetShipRuleByShopId(Db.Store, shopItemFull.ShopInfo.ShopId);

                DiliveryPrice = NoDb.ComputeDiliveryCost(ShopInfo.FreeShipAt, CartTotal, rule, address, ShopInfo.Location, customer.IsNear);

                //if (address.Region == shopItemFull.ShopInfo.Location.Region)
                //{
                //    IsNear = true;
                //    Index = customer.PreOrderShopItem.ShipCompanyIndex;
                //    if (Index == 0)
                //    {
                //        DiliveryPrice = new DiliveryPriceResult() { Price = 0, Reason = "" };
                //    }
                //}
            }
            else
            {
                Response.Redirect("UserLogon.aspx");
            }


        }
    }
}